package com.aaa.translation.controller;

import cn.hutool.core.text.UnicodeUtil;
import com.aaa.translation.demo.TransApi;
import com.aaa.translation.entity.TransRec;
import com.aaa.translation.service.TransRecService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2025/10/30 15:13
 * @description：翻译业务控制器
 * @modified By：
 * @version: 1.0
 */
@Controller
public class TranslateController {
    //百度在线翻译的app_id
    private static final String APP_ID = "20251030002486611";
    ////百度在线翻译的秘钥
    private static final String SECURITY_KEY = "E32IXgXzP6VtCYUimisC";
    @Resource
    private TransRecService transRecService;
    //请求映射地址
    @RequestMapping("translate")
    //响应类型
    @ResponseBody
    public String  execTranslate(String fromText,String lang)  {
        String toString="";
        System.out.println("开始翻译了:fromText"+fromText+"lang:"+lang);
        //判断本地数据库是否有符合原文的翻译记录
        TransRec queryByFromTextAndLanguage = transRecService.queryByFromTextAndLanguage(fromText, lang);
        if(null!=queryByFromTextAndLanguage&&queryByFromTextAndLanguage.getToText()!=null){
            toString=queryByFromTextAndLanguage.getToText();
            System.out.println("调用本地数据库，翻译结果："+toString);
            //直接返回翻译结果
            return toString;
        }
        //构建一个百度翻译api对象
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        String query = fromText;

        try {
            //访问百度的翻译api获取翻译的结果
            System.out.println("开始访问百度api翻译了:fromText"+fromText+"lang:"+lang);
            String result=api.getTransResult(query, "auto", lang);
            //结果解析
            String[] split = result.split("\"dst\"");
            String s = split[1].replace(":\"","").replace("\"}]}","");
            //将unicode编码转成中文
             toString= UnicodeUtil.toString(s);
           //将正常的翻译信息保存到数据库中
            TransRec transRec = new TransRec ();
            transRec.setFromText(fromText);
            transRec.setToText(toString);
            transRec.setLang(lang);
            transRecService.insert(transRec);
        } catch (Exception e) {
            //返回错误信息
            toString="翻译失败，错误信息"+e.toString();
        }
        System.out.println(toString);
        return toString;
    };
}
